// 该文件用于:
// 向外部提供一个路由器
// 指定路由规则
// 引入Vue
import Vue from 'vue';
// 引入VueRouter
import VueRouter from 'vue-router';
import store from "@/store"
// 引入路由规则
import routes from "./routes"
// 应用VueRouter这个插件
Vue.use(VueRouter)


// 重写push|replace方法
const routerPush = VueRouter.prototype.push
const routerReplace = VueRouter.prototype.replace
// 重写push方法
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve || reject) return routerPush.call(this, location, resolve, reject)
    return routerPush.call(this, location).catch(error => error)
}
// 重写replace方法
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve || reject) return routerReplace.call(this, location, resolve, reject)
    return routerReplace.call(this, location).catch(error => error)
}
// 路由器
const router = new VueRouter({
    // 路由规则
    routes,
    // 指定工作模式
    // mode:"hash",
    // 设置滚动行为
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
})


// 全局路由守卫
import { reqShopCart } from "@/api"
router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token
    let name = store.state.user.usetInfo.name
    if(token){
        console.log('>>>>');
        (async function(){
            let result = await reqShopCart()
            localStorage.setItem("shopSum",result.data[0].cartInfoList.length)
        })()
        
    }else{
        localStorage.setItem("shopSum",0)
    }

    if (token) {
        if (to.path == "/login" || to.path == "/register") {
            next("/");
        } else {
            // 登录了没有用户信息
            // 登录了用户信息过期
            if (name) {
                next();
            } else {
                try {
                    // 获取用户信息
                    await store.dispatch("getUserInfo")
                    next({ ...to });
                } catch (e) {
                    // token 失效
                    await store.dispatch("userLogin")
                    // 跳转到登录页面
                    next("/login")
                }
            }
        }
    } else {
        // 如果没有token
        let toPath = to.path;
        if (toPath.indexOf("/shopCart") !== -1 || toPath.indexOf("/myIndent") !== -1 || toPath.indexOf("/collection") !== -1 || toPath.indexOf("/confirmOrder") !== -1) {
            // 骚操作
            next("/login?redirect=" + toPath);
        } else {
            // 去的不是上面的路由
            next();
        }

    }

})

// 暴router
export default router